package com.CampaignManager.client;

import java.util.Date;

import com.CampaignManager.shared.CalendarUtil;
import com.CampaignManager.shared.CityDTO;
import com.CampaignManager.shared.JobDTO;
import com.CampaignManager.shared.PlayerCityDTO;
import com.CampaignManager.shared.PlayerDTO;
import com.CampaignManager.shared.ResourceAmountDTO;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.i18n.client.DateTimeFormat;
import com.google.gwt.maps.client.geom.LatLng;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Anchor;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.FlexTable;
import com.google.gwt.user.client.ui.Widget;

public class ActivitiesForm extends Composite {

	private static ActivitiesFormUiBinder uiBinder = GWT
			.create(ActivitiesFormUiBinder.class);

	interface ActivitiesFormUiBinder extends UiBinder<Widget, ActivitiesForm> {
	}

	private CampaignManager mainForm = null;
	private PlayerDTO playerInfo = null;
	
	public ActivitiesForm(CampaignManager manager, final PlayerDTO playerInfo) {
		
		this.mainForm = manager;
		this.playerInfo = playerInfo;
		
		initWidget(uiBinder.createAndBindUi(this));
		
		resourceForm.RefreshTable(playerInfo);
		
		DisplayJobs((JobDTO[]) playerInfo.getJobs().toArray(new JobDTO[0]));
		
		mainForm.campaignService.GetJobs(playerInfo.getEmailAddress(), new AsyncCallback<JobDTO[]>() {
    		public void onFailure(Throwable error) {
    			mainForm.handleError(error);
			}
			public void onSuccess(JobDTO[] jobs) {
				playerInfo.getJobs().clear();
				for (JobDTO job : jobs) {				
					playerInfo.getJobs().add(job);
				}
				DisplayJobs(jobs);
			}
		});
	}

	@UiField
	FlexTable jobsTable;
	
	@UiField
	ResourceForm resourceForm;
	
	private void DisplayJobs(JobDTO[] jobs) {
		
		jobsTable.removeAllRows();
		
		jobsTable.getCellFormatter().setWidth(0, 0, "50");
		
		jobsTable.setText(0, 1, "Status");
		jobsTable.setText(0, 2, "Job");
		jobsTable.setText(0, 3, "Story");
		jobsTable.setText(0, 4, "Reward");
		jobsTable.setText(0, 5, "Date Taken");
		
		jobsTable.getRowFormatter().addStyleName(0, "watchListHeader");
		jobsTable.addStyleName("watchList");
		jobsTable.getCellFormatter().addStyleName(0, 4, "watchListNumericColumn");
		
		for (JobDTO job : jobs) {
			DisplayJobRow(job);
		}
	}	
	public void DisplayJobRow(final JobDTO job) {
		final int row = jobsTable.getRowCount();
		DisplayJobRow(job, row);
	}
	@SuppressWarnings("deprecation")
	public void DisplayJobRow(final JobDTO job, final int row) {
		
		if (job.getStatus().equals("Incomplete")) {
			if (job.getJobType().equals("Delivery") || job.getJobType().equals("Escort")) {
				jobsTable.setWidget(row, 0, CompleteDeliveryButton(job, row));
			} else if (job.getJobType().equals("Surveillance") || 
					   job.getJobType().equals("Bribe") || 
					   (job.getJobType().equals("Warmonger") && job.getReward() < 3)) {
				jobsTable.setWidget(row, 0, CompleteEspionageButton(job, row));
			}			
		}
						
		jobsTable.setText(row, 1, job.getStatus());
		jobsTable.setText(row, 2, job.getJobDescription());
		
		Anchor nameLink = new Anchor(job.getStorySubject());
		nameLink.setHref("http://groups.google.com/groups?threadm="+job.getStoryMessageID());
		nameLink.setTarget("_blank");
		jobsTable.setWidget(row, 3, nameLink);
		
		jobsTable.setText(row, 4, job.getReward().toString());
		jobsTable.getCellFormatter().addStyleName(row, 4, "watchListNumericColumn");
		
		jobsTable.setText(row, 5, DateTimeFormat.getShortDateFormat().format(job.getTaken()));
	}
	
	private Button CompleteDeliveryButton(final JobDTO job, final int row) {
		
		final Button btnComplete = new Button("Complete");
		btnComplete.addClickHandler(new ClickHandler() {			
			@Override
			public void onClick(ClickEvent event) {
				btnComplete.setEnabled(false);
				btnComplete.setText("Completing...");
				mainForm.campaignService.CompleteJob(job, new AsyncCallback<Void>() {
		    		public void onFailure(Throwable error) {
		    			mainForm.handleError(error);
					}
					public void onSuccess(Void result) {
						job.setStatus("Complete");
						jobsTable.setText(row, 1, job.getStatus());
						btnComplete.setText("Complete");
						btnComplete.setVisible(false);
						
						PlayerCityDTO pcd = playerInfo.getCity(job.getJobFor());
						ResourceAmountDTO playerGold = playerInfo.getResource("Gold");
						playerGold.setAmount(playerGold.getAmount()+Math.round(job.getReward()+(.1*pcd.getFavor())));
						pcd.setFavor(pcd.getFavor()+1);	
						
						resourceForm.RefreshTable(playerInfo);
					}
				});		
			}
		});
		btnComplete.setEnabled(false);
		btnComplete.setTitle("Not near this city...");
		for (CityDTO city : mainForm.Cities) {
			if (city.getName().equals(job.getDestination())) {
				LatLng cityLoc = LatLng.newInstance(city.getLatitude(), city.getLongitude());
				LatLng playLoc = MapUtils.GetCurrentLocation(playerInfo);
				double dist = playLoc.distanceFrom(cityLoc);
				dist = dist * PlayerDTO.MILES_TO_LATLONG;
				if (dist <= PlayerDTO.FORAGE_MILES) {
					btnComplete.setEnabled(true);
					btnComplete.setTitle("Push to Complete");
				}
			}
		}
		return btnComplete;
	}
	
	private Button CompleteEspionageButton(final JobDTO job, final int row) {
		
		final Button btnComplete = new Button("Complete");
		btnComplete.addClickHandler(new ClickHandler() {			
			@Override
			public void onClick(ClickEvent event) {
				btnComplete.setEnabled(false);
				btnComplete.setText("Completing...");
				mainForm.campaignService.CompleteJob(job, new AsyncCallback<Void>() {
		    		public void onFailure(Throwable error) {
		    			mainForm.handleError(error);
					}
					public void onSuccess(Void result) {
						job.setStatus("Complete");
						jobsTable.setText(row, 1, job.getStatus());
						btnComplete.setText("Complete");
						btnComplete.setVisible(false);
						
						PlayerCityDTO pcd = playerInfo.getCity(job.getJobFor());
						if (job.getJobType().equals("Warmonger")) {
							for (CityDTO city : mainForm.Cities) {
								if (city.getName().equals(job.getJobFor())) {
									ResourceAmountDTO cr = city.getRelation(job.getDestination());
									cr.setAmount(cr.getAmount()-job.getReward());
								}
							}
						} else {
							pcd.setLeverage(pcd.getLeverage()+(2*job.getReward()));
						}
					}
				});		
			}
		});		
		if (CalendarUtil.getDaysBetween(job.getTaken(),  new Date()) >= (2*job.getReward()))
			btnComplete.setEnabled(true);
		else {
			btnComplete.setEnabled(false);
			Long duration = 2L*job.getReward();
			btnComplete.setTitle("In Progress, durration is "+duration.toString()+" days");
		}
		
		return btnComplete;
	}
	
}
